const express = require("express");
const router = express.Router();
const process = require("process");
const { spawnSync } = require("child_process");
const path = require("path");
const fs = require("fs");
const FormData = require("form-data");
const axios = require("axios");

router.get("/", function (req, res) {
  res.redirect("/static/index.html");
});

router.get("/local-ip", (req, res) => {
  const interfaces = require("os").networkInterfaces();
  for (let devName in interfaces) {
    const iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (
        alias.family === "IPv4" &&
        alias.address !== "127.0.0.1" &&
        !alias.internal
      ) {
        return res.json({ ip: alias.address });
      }
    }
  }
});

router.get("/initial-list", (req, res) => {
  const fileNodes = fs.readdirSync(
    path.join(process.cwd(), "app", "input_images")
  );
  fileNodes.sort((a, b) => {
    return Number(a.split(".")[0]) - Number(b.split(".")[0]);
  });
  return res.json(fileNodes);
});

router.get("/initial/:name", (req, res) => {
  const imgPath = path.join(
    process.cwd(),
    "app",
    "input_images",
    req.params.name
  );
  const stream = fs.createReadStream(imgPath);
  stream.on("data", (chunk) => {
    res.write(chunk);
  });
  stream.on("end", () => {
    res.status(200);
    res.end();
  });
});

router.get("/processed-list", (req, res) => {
  const fileNodes = fs.readdirSync(
    path.join(process.cwd(), "app", "output_images")
  );
  fileNodes.sort((a, b) => {
    return Number(a.split(".")[0]) - Number(b.split(".")[0]);
  });
  return res.json(fileNodes);
});

router.get("/processed/:name", (req, res) => {
  const imgPath = path.join(
    process.cwd(),
    "app",
    "output_images",
    req.params.name
  );
  const stream = fs.createReadStream(imgPath);
  stream.on("data", (chunk) => {
    res.write(chunk);
  });
  stream.on("end", () => {
    res.status(200);
    res.end();
  });
});

router.post("/run-process", (req, res) => {
  const cmds = [];
  cmds.push("preprocess_new.py");
  cmds.push("--interval");
  cmds.push(req.body.interval);
  cmds.push("--light");
  cmds.push(req.body.light);
  // cmds.push("--fog");
  // cmds.push(req.body.fog);
  cmds.push("--noise");
  cmds.push(req.body.noise);
  cmds.push("--geo");
  cmds.push(req.body.geo);
  cmds.push("--scale");
  cmds.push(req.body.scale);
  const child = spawnSync("python", cmds, {
    cwd: path.join(process.cwd(), "app"),
  });
  if (child.status !== 0) {
    console.log(child.stderr.toString());
    return res.json({
      code: 1,
      message: "处理图片失败",
    });
  }
  return res.json({ code: 0, message: "处理图片成功" });
});

function saveToDataset() {
  const mapPath = path.join(
    process.cwd(),
    "public",
    "images",
    "global-view.jpg"
  );
  const inputPath = path.join(process.cwd(), "app", "input_images");
  const outputPath = path.join(process.cwd(), "app", "output_images");
  const formData = new FormData();
  formData.append("img_bigs", fs.createReadStream(mapPath));
  fs.readdirSync(inputPath).forEach((item) => {
    const filePath = path.join(inputPath, item);
    formData.append("img_orins", fs.createReadStream(filePath));
  });
  fs.readdirSync(outputPath).forEach((item) => {
    const filePath = path.join(outputPath, item);
    formData.append("img_deals", fs.createReadStream(filePath));
  });
  formData.append("frequency", req.body.interval);
  formData.append("light", req.body.light);
  // formData.append("smog", req.body.fog);
  formData.append("white_noise", req.body.white);
  formData.append("noise", req.body.gaussian);
  formData.append("obscure", req.body.blur);
  console.log(req.app.locals.taskInfo);
  const taskMap = {
    horizontal: 1,
    vertical: 2,
    diagonal: 3,
  };
  formData.append("locus", taskMap[req.app.locals.taskInfo.traj]);
  formData.append("angle", req.app.locals.taskInfo.angle);
  axios
    .post(
      `http://192.168.10.5:8081/export/img`,
      formData,
      formData.getHeaders()
    )
    .then((result) => {
      console.log(result.data);
    })
    .catch((err) => {
      console.log("request error");
    });
}

router.post("/tran-image", async (req, res) => {
  try {
    // 初始化目标服务器文件夹
    await axios.get(`http://${req.body.ip}:${req.body.port}/api/init`);
    const fileNodes = fs.readdirSync(
      path.join(process.cwd(), "app", "output_images")
    );
    for (let i = 0; i < fileNodes.length; i++) {
      const formData = new FormData();
      const imgPath = path.join(
        process.cwd(),
        "app",
        "output_images",
        fileNodes[i]
      );
      formData.append("image", fs.createReadStream(imgPath));
      await axios.post(
        `http://${req.body.ip}:${req.body.port}/api/upload`,
        formData,
        formData.getHeaders()
      );
      req.app.locals.ws.send(
        `tran ${Math.round(i / (fileNodes.length - 1)) * 100}`
      );
    }
    req.app.locals.ws.send("tran done");
    // 激活下位机
    await axios.post(
      `http://${req.body.ip}:${req.body.port}/api/run`,
      req.app.locals.taskInfo
    );
    return res.json({ code: 0, message: "文件传输结束" });
  } catch (err) {
    return res.json({ code: 1, message: "下位机激活失败" });
  }
});

module.exports = router;
